package com.happy.study.controller;

import com.alibaba.fastjson.JSONArray;
import com.happy.study.entity.AnswerEntity;
import com.happy.study.entity.RecordEntity;
import com.happy.study.entity.UserEntity;
import com.happy.study.servier.IAnswerService;
import com.happy.study.servier.IRecordService;
import com.happy.study.util.ResultBody;
import com.happy.study.util.StateEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping ("/answer")
public class AnswerController {

    @Resource
    private IAnswerService iAnswerService;
    @Resource
    private IRecordService iRecordService;

    /**
     * 交卷: 添加答案，添加考试记录
     *
     * @param answerEntities
     * @param session
     * @return
     */
    @PostMapping (value = "/addBatch")
    @ResponseBody
    public ResultBody<AnswerEntity> addBatch ( String answerEntities, String paperId, HttpSession session ) {
        List<AnswerEntity> answerEntityList = JSONArray.parseArray ( answerEntities, AnswerEntity.class );
        UserEntity userEntity = (UserEntity) session.getAttribute ( "userEntity" );
        if ( userEntity == null ) {
            return ResultBody.fail ( StateEnum.REQUEST_POWER_EXCE );
        }
        RecordEntity recordEntity = new RecordEntity ();
        recordEntity.setUserId ( userEntity.getId () );
        recordEntity.setPaperId ( Integer.parseInt ( paperId ) );
        recordEntity = iRecordService.addSingle ( recordEntity );
        boolean flag = iAnswerService.addBatch ( answerEntityList, userEntity, recordEntity.getId () );
        if ( ! flag ) {
            return ResultBody.fail ( StateEnum.INSERT_EXCE );
        }
        return ResultBody.success ();
    }


}
